local skynet = require "skynet"
local socket = require "socket"

local clients = {}

skynet.start(function()
  skynet.error("[main] start")

  local listenfd = socket.listen("127.0.0.1", 9001)
  skynet.error("[main] Listen on 127.0.0.1:9001")

  socket.start(listenfd, function(fd, addr)
    skynet.error("[socket] client connected", fd)

    local svc = skynet.newservice("echo")
    skynet.send(svc, "lua", "start", fd)

    clients[fd] = svc
  end)

  local function broadcast()
    for fd, svc in pairs(clients) do
      pcall(skynet.send, svc, "lua", "broadcast", "[broadcast] hello at " .. os.date())
    end
    skynet.timeout(100, broadcast)
  end

  skynet.timeout(100, broadcast)

  skynet.dispatch("lua", function(_, _, cmd, ...)
    if cmd == "client_exit" then
      local fd = ...
      clients[fd] = nil
      skynet.error("[main] client fd closed", fd)
    end
  end)
end)
